package ws

import (
	"ims/app/dao"
	"log"

	"github.com/gogf/gf/net/ghttp"
)

var ChatRoom = make(map[string]*Wsconn)
var PingClient = make(map[string]*PingInfo)
var APPID = "202116257358989495"

//测试新版的 用于建立客服端建立wscoket 通信的服务器
func PageNewChatServer(r *ghttp.Request) {
	conn, err := upgrader.Upgrade(r.Response.Writer, r.Request, nil)
	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	visitorType := r.GetString("type")
	token := r.GetString("token")
	//user 类型visitorType， 链接时 token 是用来去查询 默认客服进行对话
	//而 kefu类型 ，token是用来验证 jwt是否正确的。
	// log.Println(token, visitorType)
	if visitorType != "kefu" && visitorType != "user" && visitorType != "admin" {
		conn.Close()
	}
	if token == "" {
		conn.Close()
	}

	// 验证客服链接的token是否正确
	if visitorType == "kefu" {
		kefu, _ := KefuLogin(token)
		if kefu != nil {
			AddToChatRoom(conn, kefu)
		} else {
			conn.Close()

		}

	}
	//验证 用户链接的token是否正确
	if visitorType == "user" {
		appInfo := dao.ChatApplication.ParseToken(token)
		if appInfo.Appid == "" {
			conn.Close()
		}
	}

	//发送欢迎的ping表示服务器响应ws请求
	SendWelcomePing(conn)
	SendClientAppid(conn)
	//把当前客户加入ClientList

	for {
		//接受消息
		var receive []byte
		messageType, receive, err := conn.ReadMessage()
		if err != nil {
			// for _, visitor := range ClientList {
			// 	if visitor.Conn == conn {
			// 		log.Println("删除用户", visitor.Id)
			// 		delete(ClientList, visitor.Id)
			// 		VisitorOffline(visitor.To_id, visitor.Id, visitor.Name)
			// 	}
			// }
			log.Println(err)
			return
		}

		message <- &Message{
			conn:        conn,
			content:     receive,
			context:     r.Context(),
			messageType: messageType,
		}
	}
}
